package day12.network;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.sql.SQLOutput;
import java.util.Scanner;

public class Server1 {
    public static void main(String[] args) throws IOException {
        //在本机8000端口上启动服务
        // 如果端口被占用,这里会出现异常
        new Thread(){
            public void run() {
                try {
                    ServerSocket server = new ServerSocket(8000);
                    System.out.println("服务器已启动");
                    while (true){
                        Socket s = server.accept();
                        ComThread t = new ComThread(s);
                        t.start();
                    }
                } catch (IOException e) {
                    System.out.println("服务器已断开连接");

                }
            }
        }.start();


        //等待客户端发起连接请求，建立连接通道

            // 从连接通道获取流
            //InputStream in = s.getInputStream();
            //OutputStream out = s.getOutputStream();

        /*
        通信协议
        通信流程，数据格式
        1. 接收五个字符 Hello
        2. 向对方发送5个字符 world
         */
//        for (int i = 0; i < 5; i++) {
//            char c = (char) in.read();
//            System.out.print(c);
//        }
//
//        out.write("world".getBytes());
//        out.flush();


        }



    static class ComThread extends Thread {
        Socket s;

        public ComThread(Socket s) {
            this.s = s;
        }

        @Override
        public void run() {

            try {
                BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                // Printer 有println方法
                PrintWriter out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
                String line;
                while((line = in.readLine()) != null){
                    System.out.println(line);
                }
                System.out.print(">>");
                String str = new Scanner(System.in).nextLine();
                out.println(str);
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }

}
